package validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import command.EmailForm;

@Component
public class EmailFormValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return EmailForm.class.equals(clazz);
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		EmailForm form = (EmailForm) target;
		if (form.getFrom() == null || form.getFrom().isEmpty()) {
			errors.rejectValue("from", "empty");
		} else if (!form.getFrom().matches("^[\\w\\-\\_\\+]+(\\.[\\w\\-\\_]+)*@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$")) {
			errors.rejectValue("from", "invalid");
		} else if (form.getFrom().length() > 100) {
			errors.rejectValue("from", "tooLong");
		}
		if (form.getTo() == null || form.getTo().length == 0) {
			errors.rejectValue("to", "empty");
		} 
	}
}